#include "InfoBoxUI.h"
#include "ui_infobox.h"

#include <QTimer>
#include <QGraphicsOpacityEffect>

InfoBoxUI::InfoBoxUI(const QString &message, int displayTime,
                     QWidget *parent) :
    QWidget(parent),
    ui(new Ui::InfoBoxUI)
{
    ui->setupUi(this);
    ui->infoLabel->setText(message);

    setStyleSheet("QWidget { background : #ffffff }");

    // Center box on parent widget
    move(parent->geometry().center() - geometry().center());

    // Create fade effect
    fadeEffect = new QGraphicsOpacityEffect();
    fadeEffect->setProperty("opacity", 0.8);
    setGraphicsEffect(fadeEffect);

    // Fade in animation
    animation = new QPropertyAnimation(fadeEffect, "opacity");
    animation->setStartValue(0.0);
    animation->setEndValue(0.8);
    animation->setDuration(200);
    animation->start();

    // Create timer to fade out
    QTimer::singleShot(displayTime, this, SLOT(startClose()));

    show();
}

void InfoBoxUI::startClose()
{
    // Fade out animation
    animation = new QPropertyAnimation(fadeEffect, "opacity");
    animation->setStartValue(0.8);
    animation->setEndValue(0.0);
    animation->setDuration(500);

    connect(animation, SIGNAL(finished()), this, SLOT(finishClose()));
    animation->start();
}

void InfoBoxUI::finishClose()
{
    deleteLater();
}

InfoBoxUI::~InfoBoxUI()
{
    delete animation;
    delete fadeEffect;

    delete ui;
}
